package com.syf.core.kit;

import com.syf.core.exception.ToolKitNotFoundException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * tool kit manager，将starter中定义的各kit对象加载、查询及关闭
 */
public class SyToolKitProvider implements ToolKitProvider, BeanPostProcessor {

    private Map<Class, Object> kitMap = new ConcurrentHashMap<>(16);

    @Override
    public <T> T getToolKit(Class<T> kitClazz) throws ToolKitNotFoundException {
        return (T) kitMap.get(kitClazz);
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        // 查询bean对象带@SyFrameKit
        Class<?> beanClass = bean.getClass();
        if (beanClass.getName().contains("$$EnhancerBySpringCGLIB")) { //com.framework.core.config.properties.DataSourcesConfig$$EnhancerBySpringCGLIB$$2ce4b8f3
            beanClass = bean.getClass().getSuperclass();
        }

        SyFrameKit syKitAnno = beanClass.getAnnotation(SyFrameKit.class);
        if (syKitAnno != null) {
            kitMap.put(beanClass, bean);
        }

        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}
